<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h2 class="page-header">axios取消请求</h2>
            <button class="btn btn-primary">发送请求</button>
            <button class="btn btn-warning">取消请求</button>
        </div>
        <script>
            //获取按钮
            const btn = document.querySelectorAll("button");
            // 2.声明全局变量
            let cancel = null;
            btn[0].onclick = function(){
                if(cancel != null){
                    cancel();//取消上一次的请求
                }
                axios({
                    methods: "get",
                    url:"http://127.0.0.1:3000/posts",
                    //1.添加配置对象的属性
                    cancelToken:new axios.CancelToken(function(c){
                        console.log(c);
                        // 3.将c的值赋值给cancel
                        cancel = c;
                    })
                }).then(response =>{
                    console.log(response);
                    // 将cancel的值初始化设置
                    cancel = null;
                })
            } 

            btn[1].onclick = function(){
                cancel();
            }
        </script>
    </body>
</html>